package JMH.day05;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 通过JMH工具对别ArrayList和LinkedList的查找效率。
 * Benchmark                                                   Mode  Cnt      Score      Error  Units
 * JMH.day05.LinkedListVsArrayList.binarySearchFromArrayList   avgt   20      0.141 ±    0.001  us/op
 * JMH.day05.LinkedListVsArrayList.binarySearchFromLinkedList  avgt   20  18589.678 ± 1048.019  us/op
 */
@Warmup(iterations = 20)
@Measurement(iterations = 20)
@State(Scope.Thread)
@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class LinkedListVsArrayList {

    private LinkedList<Integer> linkedList;
    private List<Integer> list;
    private Random random;

    @Setup
    public void setUp() {
        linkedList = new LinkedList<>();
        list = new ArrayList<>();
        random = new Random(System.currentTimeMillis());
        for (int i = 0; i < 10_000_000; i++) {
            list.add(i);
            linkedList.add(i);
        }
    }

    @Benchmark
    public void binarySearchFromArrayList(Blackhole blackhole) {
        int i = random.nextInt(10_000_000);
        Integer integer = list.get(i);
        blackhole.consume(integer);
    }

    @Benchmark
    public void binarySearchFromLinkedList(Blackhole blackhole) {
        int i = random.nextInt(10_000_000);
        Integer integer = linkedList.get(i);
        blackhole.consume(integer);
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(LinkedListVsArrayList.class.getSimpleName())
                .build();
        new Runner(options).run();
    }
}
